package com.xunua.networkproject.Utils;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @user XUNUA
 * @email xunua@outlook.com
 * @creat time 2020/4/26 1:32
 *
 *         post请求参照此：https://blog.csdn.net/w605283073/article/details/103797118?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158784284619725222431143%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=158784284619725222431143&biz_id=0&utm_source=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_v25-1
 *
 *     //okhttp3
 *     implementation("com.squareup.okhttp3:okhttp:4.5.0")
 *
 */
public class OkHttpUtils  {
    /**
     *  get请求（常用）
     * @param url       url参数是链接地址
     * @return
     * @throws IOException
     */
    public String get(String url) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(100000, TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }


    /**
     * Post请求（常用）       这个是key value形式
     * 标准请求，将post请求数据写在hashmap中 进行遍历
     * @param url               url参数是链接地址
     * @param hashMap           这个是post请求的key value        hashmap.put("请求key1","value1")  hashmap.put("请求key2","value2")
     * @return
     * @throws IOException
     */
    public String post(String url, HashMap<String,String> hashMap) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(100000, TimeUnit.MILLISECONDS)
                .build();
        FormBody.Builder builder = new FormBody.Builder();
        for (String key:
                hashMap.keySet()) {
            builder.add(key, hashMap.get(key));
        }
        RequestBody body = builder
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     * post请求    这个是json数据形式
     *
     *这个post请求是发送json数据来进行请求   与上面的不一样    （这个不常用）  只是官网有这个方法，就留在这里
     */
    public static final MediaType JSON
            = MediaType.get("application/json; charset=utf-8");
    String post(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(100000, TimeUnit.MILLISECONDS)
                .build();
        RequestBody body = RequestBody.create(json, JSON);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    /**
     *     OkHttp上传单个文件
     * @param uri   接口地址
     * @param context   上下文
     * @param fileUri   文件的uri地址 不再是path路径了  分区存储后只能先得到文件的uri
     * @return      返回response  记得判断返回值是否为null
     */
    public static Response upload(String uri, Context context,Uri fileUri){
        InputStream inputStream=null;
        Response response=null;
        try {
            //client
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .build();

            String path = FileUtils.getPath(context, fileUri);//通过uri得到了文件的绝对路径
            File file = new File(path);//特定新建一个file类
            String fileName = file.getName();//来获取文件名  主要是文件名的后缀
            inputStream = context.getContentResolver().openInputStream(fileUri);

            byte[] bytes = FileUtils.toByteArray(inputStream);

            String type = context.getContentResolver().getType(fileUri);
            RequestBody requestBody = RequestBody.create(bytes, MediaType.parse(type));
            MultipartBody multipartBody = new MultipartBody.Builder()
                    .addFormDataPart("file",fileName, requestBody)
                    .build();
            Request request = new Request.Builder()
                    .url(String.valueOf(uri))
                    .post(multipartBody)
                    .build();
            response = client.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * OkHttp上传多个文件      支持上传视频
     * @param uri       接口的uri地址
     * @param fileUris     存放上传文件的uri地址的集合
     * @param context       上下文
     */
    void uploads(String uri,List<Uri> fileUris,Context context){
        InputStream inputStream=null;
        try {
            //client
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .build();
            MultipartBody.Builder mulBuilder = new MultipartBody.Builder();
            for (Uri fileUri:
                    fileUris) {
                String path = FileUtils.getPath(context,fileUri);
                File file = new File(path);
                String fileName = file.getName();
                inputStream=context.getContentResolver().openInputStream(fileUri);
                byte[] bytes = FileUtils.toByteArray(inputStream);
                RequestBody requestBody = RequestBody.create(bytes, MediaType.parse(context.getContentResolver().getType(fileUri)));
                mulBuilder.addFormDataPart("files",fileName,requestBody);
            }
            MultipartBody multipartBody = mulBuilder.build();
            Request request = new Request.Builder()
                    .url(uri)
                    .post(multipartBody)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
